<template>
  <view class="chat-page">
    <!-- 自定义导航栏 -->
    <!--    <view class="custom-navbar">-->
    <!--      <view class="navbar-content">-->
    <!--        <view class="navbar-left" @click="goBack">-->
    <!--          <u-icon name="arrow-left" color="#fff" size="20"></u-icon>-->
    <!--        </view>-->

    <!--        <view class="navbar-center">-->
    <!--          <view class="chat-info">-->
    <!--            <text class="chat-title">{{ conversationName }}</text>-->
    <!--            <text class="chat-status">在线</text>-->
    <!--          </view>-->
    <!--        </view>-->

    <!--        <view class="navbar-right">-->
    <!--          <u-icon name="more-dot-fill" color="#fff" size="20" @click="showMoreMenu = true"></u-icon>-->
    <!--        </view>-->
    <!--      </view>-->
    <!--    </view>-->

    <!-- 消息列表 -->
    <scroll-view
        class="message-list"
        scroll-y
        :scroll-top="scrollTop"
        :scroll-into-view="scrollIntoView"
        @scrolltoupper="loadMoreMessages"
    >
      <!-- 顶部加载更多提示 -->
      <view class="load-more-tip" v-if="messageList.length > 0">
        <text>没有更多消息了</text>
      </view>

      <view v-for="message in messageList" :key="message.id" :id="`msg-${message.id}`" class="message-wrapper">
        <!-- 时间分割线 -->
        <view v-if="shouldShowTime(message)" class="time-divider">
          <view class="time-badge">
            <text class="time-text">{{ formatMessageTime(message.createdAt) }}</text>
          </view>
        </view>

        <!-- 消息项 -->
        <view class="message-item" :class="{ 'own-message': isOwnMessage(message) }">
          <view class="avatar-wrapper">
            <u-avatar
                :src="getUserAvatar(message)"
                :size="40"
            ></u-avatar>
          </view>

          <view class="message-content-wrapper">
            <!-- 文本消息 -->
            <view
                v-if="message.contentType === 'TEXT'"
                class="text-message"
                :class="{ 'own-text': isOwnMessage(message) }"
            >
              <text class="message-text">{{ message.content }}</text>
            </view>

            <!-- 图片消息 -->
            <view
                v-else-if="message.contentType === 'IMAGE'"
                class="image-message"
                @click="previewImage(message.content)"
            >
              <image :src="message.content" mode="aspectFill"></image>
            </view>

            <!-- 其他类型消息 -->
            <view v-else class="other-message">
              <text>{{ getMessageTypeText(message.contentType) }}</text>
            </view>

            <!-- 消息状态 -->
            <view class="message-status" v-if="isOwnMessage(message)">
              <text v-if="message.status === 'SENDING'" class="status-sending">发送中</text>
              <text v-else-if="message.status === 'SENT'" class="status-sent">已送达</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 正在输入提示 -->
      <view v-if="isTyping" class="typing-indicator">
        <text>对方正在输入...</text>
      </view>
    </scroll-view>

    <!-- 输入区域 -->
    <view class="input-section">
      <view class="input-bar">
        <!-- <view class="icon-btn plus-btn" @click="showToolbar = !showToolbar">
          <u-icon :name="showToolbar ? 'close-circle' : 'plus-circle'" size="24"
                  :color="showToolbar ? '#4CAF50' : '#999'"></u-icon>
        </view> -->

        <view class="input-wrapper">
          <u-input
              v-model="inputText"
              placeholder="输入消息..."
              :border="false"
              :custom-style="{ backgroundColor: '#f8f8f8', borderRadius: '24rpx', padding: '16rpx 24rpx' }"
              @focus="handleInputFocus"
              @blur="handleInputBlur"
              @input="handleInputChange"
              @confirm="sendMessage"
          ></u-input>
        </view>

        <view v-if="inputText.trim()" class="send-btn" @click="sendMessage">
          <u-icon name="arrow-right" size="20" color="#fff"></u-icon>
        </view>
        <view v-else class="icon-btn" @click="startVoiceRecord">
          <u-icon name="mic" size="24" color="#999"></u-icon>
        </view>
      </view>

      <!-- 工具栏 -->
      <transition name="toolbar-slide">
        <view v-if="showToolbar" class="toolbar">
          <view class="tool-item" @click="chooseImage">
            <view class="tool-icon" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);">
              <u-icon name="photo" size="28" color="#fff"></u-icon>
            </view>
            <text>相册</text>
          </view>
          <view class="tool-item" @click="takePhoto">
            <view class="tool-icon" style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);">
              <u-icon name="camera" size="28" color="#fff"></u-icon>
            </view>
            <text>拍照</text>
          </view>
          <view class="tool-item" @click="chooseFile">
            <view class="tool-icon" style="background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);">
              <u-icon name="folder" size="28" color="#fff"></u-icon>
            </view>
            <text>文件</text>
          </view>
        </view>
      </transition>
    </view>

    <!-- 更多菜单 -->
    <u-action-sheet
        v-model="showMoreMenu"
        :actions="moreActions"
        @select="handleMoreAction"
    ></u-action-sheet>
  </view>
</template>

<script>
import {getConversationMessages, markConversationAsRead} from '@/api/message'
import {formatTime} from '@/utils/date'
import WebSocketClient from '@/utils/websocket'

export default {
  name: 'MessageChat',
  data() {
    return {
      conversationId: '',
      conversationName: '',
      teacherId: null, // 教员ID（从教员列表跳转时使用）
      targetUserId: null, // 目标用户ID（对方的用户ID）
      otherUserInfo: null, // 对方用户信息（头像、昵称）
      messageList: [],
      inputText: '',
      showToolbar: false,
      showMoreMenu: false,
      isTyping: false,
      scrollTop: 0,
      scrollIntoView: '',
      loading: false,
      typingTimer: null,
      moreActions: [
        {name: '清空聊天记录', value: 'clear'},
        {name: '会话设置', value: 'setting'}
      ]
    }
  },

  onLoad(options) {
    console.log('聊天页面参数:', options)
    
    // 处理从不同页面跳转过来的情况
    if (options.teacherId) {
      // 从教员列表或详情页跳转过来，需要创建或获取会话
      this.teacherId = parseInt(options.teacherId)
      this.targetUserId = parseInt(options.teacherId) // 设置目标用户ID
      this.conversationName = decodeURIComponent(options.teacherName || '教员')
      this.otherUserInfo = {
        id: parseInt(options.teacherId),
        name: decodeURIComponent(options.teacherName || '教员'),
        avatar: options.teacherAvatar || '/static/icons/default-avatar.png'
      }
      console.log('从教员列表进入，目标用户ID:', this.targetUserId)
      // 会话ID将在loadMessages中创建
      this.conversationId = null
    } else if (options.conversationId) {
      // 从消息列表跳转过来，已有会话ID
      this.conversationId = options.conversationId
      this.conversationName = decodeURIComponent(options.name || '聊天')
      // 优先使用传入的otherUserId
      if (options.otherUserId) {
        this.targetUserId = parseInt(options.otherUserId)
        console.log('从消息列表传入的目标用户ID:', this.targetUserId)
      } else {
        // 如果没有传入，需要从会话详情获取
        console.log('未传入otherUserId，将从会话详情获取')
      }
    } else {
      // 没有任何参数，显示错误
      uni.showModal({
        title: '提示',
        content: '参数错误，请从教员列表或消息列表进入',
        showCancel: false,
        success: () => {
          uni.navigateBack()
        }
      })
      return
    }

    // 如果从消息列表进来但没有targetUserId，先获取会话详情
    if (this.conversationId && !this.targetUserId) {
      this.loadConversationDetail()
    }
    
    this.initWebSocket()
    this.loadMessages()
    this.markAsRead()
  },

  onUnload() {
    this.disconnectWebSocket()
  },

  methods: {
    // 初始化WebSocket
    initWebSocket() {
      console.log('初始化WebSocket连接...')
      
      // 检查token是否存在 - 使用正确的key
      const token = uni.getStorageSync('edu_token')
      const userInfo = uni.getStorageSync('edu_user_info')
      console.log('Token是否存在:', !!token)
      console.log('用户信息是否存在:', !!userInfo)
      
      if (!token) {
        console.error('未找到token，无法建立WebSocket连接')
        // 已经登录但是进入聊天页面才发现没token，可能是其他原因
        // 不再显示弹窗，只在控制台输出
        return
      }
      
      this.websocket = new WebSocketClient()
      this.websocket.connect()

      // 监听消息
      this.websocket.onMessage((data) => {
        console.log('收到WebSocket消息:', data)
        if (data.type === 'NEW_MESSAGE') {
          this.handleNewMessage(data.data)
        } else if (data.type === 'MESSAGE_SENT') {
          this.handleMessageSent(data.data)
        } else if (data.type === 'MESSAGE_ERROR') {
          this.handleMessageError(data.data)
        } else if (data.type === 'TYPING') {
          this.handleTypingMessage(data.data)
        } else if (data.type === 'CONNECT') {
          console.log('WebSocket连接成功消息:', data.message)
        }
      })
      
      // 延迟检查连接状态
      setTimeout(() => {
        const state = this.websocket.getConnectionState()
        console.log('WebSocket连接状态:', state)
        if (!state.isConnected) {
          console.warn('WebSocket未能成功连接')
        }
      }, 3000)
    },

    // 断开WebSocket
    disconnectWebSocket() {
      if (this.websocket) {
        this.websocket.disconnect()
      }
    },

    // 加载会话详情
    async loadConversationDetail() {
      try {
        const { getConversationDetail } = require('@/api/message')
        const res = await getConversationDetail(this.conversationId)
        
        if (res.code === 200 && res.data) {
          console.log('会话详情:', res.data)
          
          // 获取对方用户ID
          if (res.data.otherUserId) {
            this.targetUserId = res.data.otherUserId
            console.log('从会话详情获取目标用户ID:', this.targetUserId)
          } else {
            // 从participants中解析
            const userInfoStr = uni.getStorageSync('edu_user_info')
            const userInfo = userInfoStr ? JSON.parse(userInfoStr) : null
            if (userInfo && res.data.participants) {
              const participants = JSON.parse(res.data.participants)
              this.targetUserId = participants.find(id => parseInt(id) !== parseInt(userInfo.userId))
              console.log('从participants解析目标用户ID:', this.targetUserId)
            }
          }
          
          // 获取对方用户信息
          if (res.data.otherUserName) {
            this.otherUserInfo = {
              id: this.targetUserId,
              name: res.data.otherUserName,
              avatar: res.data.otherUserAvatar || '/static/icons/default-avatar.png'
            }
          }
        }
      } catch (error) {
        console.error('加载会话详情失败:', error)
      }
    },

    // 加载消息列表
    async loadMessages() {
      try {
        this.loading = true

        // 如果有教员ID但没有会话ID，需要先创建或获取会话
        if (this.teacherId && !this.conversationId) {
          console.log('获取或创建与教员的私聊会话, teacherId:', this.teacherId)
          
          try {
            // 调用API获取或创建私聊会话
            const { getPrivateConversation, createPrivateConversation } = require('@/api/message')
            
            // 先尝试获取已存在的会话
            const getRes = await getPrivateConversation(this.teacherId)
            
            if (getRes.code === 200 && getRes.data) {
              // 会话已存在，data是Conversation对象
              this.conversationId = getRes.data.id
              // 从会话数据中获取对方用户ID
              if (getRes.data.otherUserId) {
                this.targetUserId = getRes.data.otherUserId
              }
              console.log('找到已存在的会话:', this.conversationId, '对方ID:', this.targetUserId)
            } else {
              // 会话不存在，创建新会话
              const createRes = await createPrivateConversation(this.teacherId)
              if (createRes.code === 200 && createRes.data) {
                // data现在是Conversation对象
                this.conversationId = createRes.data.id || createRes.data
                if (createRes.data.otherUserId) {
                  this.targetUserId = createRes.data.otherUserId
                }
                console.log('创建新会话成功:', this.conversationId, '对方ID:', this.targetUserId)
              } else {
                throw new Error('创建会话失败')
              }
            }
          } catch (error) {
            console.error('获取或创建会话失败:', error)
            // 如果API调用失败，显示空消息列表
            this.messageList = []
            this.loading = false
            uni.showToast({
              title: '会话创建失败',
              icon: 'none'
            })
            return
          }
        }

        if (!this.conversationId) {
          console.warn('没有会话ID，无法加载消息')
          this.loading = false
          return
        }

        // 加载会话消息
        const res = await getConversationMessages(this.conversationId, 50)
        if (res.code === 200) {
          console.log('加载的消息列表:', res.data)
          this.messageList = (res.data || []).reverse()
          
          // 打印前3条消息的详细信息
          if (this.messageList.length > 0) {
            console.log('前3条消息:')
            this.messageList.slice(0, 3).forEach((msg, index) => {
              console.log(`消息${index + 1}:`, {
                id: msg.id,
                fromUserId: msg.fromUserId,
                toUserId: msg.toUserId,
                content: msg.content
              })
            })
          }
          
          // 如果还没有targetUserId，从消息中推断
          if (!this.targetUserId && this.messageList.length > 0) {
            const userInfoStr = uni.getStorageSync('edu_user_info')
            const userInfo = userInfoStr ? JSON.parse(userInfoStr) : null
            if (userInfo) {
              console.log('当前用户ID:', userInfo.userId)  // 修改：使用userId字段
              
              // 找到第一条不是自己发送的消息，获取对方ID
              const otherMessage = this.messageList.find(msg => parseInt(msg.fromUserId) !== parseInt(userInfo.userId))
              if (otherMessage) {
                this.targetUserId = otherMessage.fromUserId
                console.log('从对方消息获取目标用户ID:', this.targetUserId)
              } else {
                // 如果所有消息都是自己发的，从第一条消息的toUserId获取
                if (this.messageList[0] && this.messageList[0].toUserId) {
                  // 确保toUserId不是自己
                  if (parseInt(this.messageList[0].toUserId) !== parseInt(userInfo.userId)) {
                    this.targetUserId = this.messageList[0].toUserId
                    console.log('从自己消息的toUserId获取目标用户ID:', this.targetUserId)
                  } else {
                    console.warn('消息toUserId是自己，无法确定对方ID')
                  }
                }
              }
            }
          }
          
          console.log('最终确定的targetUserId:', this.targetUserId)
          
          this.$nextTick(() => {
            this.scrollToBottom()
          })
        }
      } catch (error) {
        console.error('加载消息失败:', error)
        // 新会话或加载失败，显示空消息列表
        this.messageList = []
        console.log('显示空消息列表')
      } finally {
        this.loading = false
      }
    },

    // 添加演示消息
    addDemoMessages() {
      const userInfoStr = uni.getStorageSync('edu_user_info')
      const userInfo = userInfoStr ? JSON.parse(userInfoStr) : {userId: 1, username: '我'}
      const currentTime = new Date()

      this.messageList = [
        {
          id: 1,
          fromUserId: 2,
          toUserId: userInfo.userId,
          content: '你好！欢迎使用家教平台的消息功能',
          contentType: 'TEXT',
          createdAt: new Date(currentTime.getTime() - 300000).toISOString(), // 5分钟前
          status: 'READ'
        },
        {
          id: 2,
          fromUserId: userInfo.userId,
          toUserId: 2,
          content: '你好！这个功能很棒',
          contentType: 'TEXT',
          createdAt: new Date(currentTime.getTime() - 240000).toISOString(), // 4分钟前
          status: 'read'
        },
        {
          id: 3,
          fromUserId: 2,
          toUserId: userInfo.userId,
          content: '是的，您可以通过这里与教员或家长进行实时沟通',
          contentType: 'TEXT',
          createdAt: new Date(currentTime.getTime() - 180000).toISOString(), // 3分钟前
          status: 'READ'
        },
        {
          id: 4,
          fromUserId: userInfo.userId,
          toUserId: 2,
          content: '太好了，这样沟通更方便了',
          contentType: 'TEXT',
          createdAt: new Date(currentTime.getTime() - 120000).toISOString(), // 2分钟前
          status: 'read'
        }
      ]
    },

    // 加载更多消息
    async loadMoreMessages() {
      // TODO: 实现分页加载更多消息
      console.log('加载更多消息')
    },

    // 发送消息
    sendMessage() {
      if (!this.inputText.trim()) return

      // 检查WebSocket连接状态
      if (!this.websocket || !this.websocket.isConnected) {
        uni.showToast({
          title: 'WebSocket未连接，请稍后重试',
          icon: 'none',
          duration: 2000
        })
        console.error('WebSocket未连接，无法发送消息')
        return
      }

      const message = {
        type: 'CHAT',
        toUserId: this.getTargetUserId(),
        content: this.inputText.trim(),
        contentType: 'TEXT'
      }

      // 通过WebSocket发送
      const success = this.websocket.send(message)
      
      if (!success) {
        uni.showToast({
          title: '消息发送失败',
          icon: 'none',
          duration: 2000
        })
        return
      }

      // 添加到本地消息列表
      this.addLocalMessage(message)

      // 清空输入框
      this.inputText = ''
      this.showToolbar = false

      // 滚动到底部
      this.$nextTick(() => {
        this.scrollToBottom()
      })
    },

    // 处理新消息
    handleNewMessage(messageData) {
      // 添加到消息列表
      this.messageList.push({
        id: messageData.messageId,
        fromUserId: messageData.fromUserId,
        content: messageData.content,
        contentType: messageData.contentType,
        createdAt: new Date().toISOString(),
        status: 'READ'
      })

      // 滚动到底部
      this.$nextTick(() => {
        this.scrollToBottom()
      })

      // 标记为已读
      this.markAsRead()
    },

    // 处理消息发送成功
    handleMessageSent(messageData) {
      console.log('消息发送成功:', messageData)
      
      // 更新本地消息状态
      const lastMessage = this.messageList[this.messageList.length - 1]
      if (lastMessage && lastMessage.status === 'SENDING') {
        lastMessage.id = messageData.messageId
        lastMessage.status = 'SENT'
      }
      
      // 显示成功提示
      uni.showToast({
        title: '发送成功',
        icon: 'success',
        duration: 1000
      })
    },

    // 处理消息发送失败
    handleMessageError(errorData) {
      console.error('消息发送失败:', errorData)
      
      // 更新本地消息状态为失败
      const lastMessage = this.messageList[this.messageList.length - 1]
      if (lastMessage && lastMessage.status === 'SENDING') {
        lastMessage.status = 'FAILED'
      }
      
      // 显示错误提示
      uni.showToast({
        title: '发送失败: ' + (errorData.error || '未知错误'),
        icon: 'none',
        duration: 2000
      })
    },

    // 处理正在输入消息
    handleTypingMessage(data) {
      this.isTyping = data.isTyping
      if (this.isTyping) {
        // 3秒后自动隐藏
        setTimeout(() => {
          this.isTyping = false
        }, 3000)
      }
    },

    // 添加本地消息
    addLocalMessage(message) {
      // 使用正确的key获取用户信息
      const userInfoStr = uni.getStorageSync('edu_user_info')
      const userInfo = userInfoStr ? JSON.parse(userInfoStr) : {userId: 1}
      
      console.log('添加本地消息，当前用户:', userInfo)
      
      const localMessage = {
        id: Date.now(),
        fromUserId: userInfo.userId,  // 修改：使用userId字段
        toUserId: this.targetUserId,
        content: message.content,
        contentType: message.contentType,
        createdAt: new Date().toISOString(),
        status: 'SENDING'
      }
      
      console.log('本地消息对象:', localMessage)
      
      this.messageList.push(localMessage)
    },

    // 输入框获得焦点
    handleInputFocus() {
      this.showToolbar = false
      this.$nextTick(() => {
        this.scrollToBottom()
      })
    },

    // 输入框失去焦点
    handleInputBlur() {
      // 发送停止输入消息
      this.sendTypingMessage(false)
    },

    // 输入内容变化
    handleInputChange() {
      // 发送正在输入消息
      this.sendTypingMessage(true)

      // 清除之前的定时器
      if (this.typingTimer) {
        clearTimeout(this.typingTimer)
      }

      // 3秒后发送停止输入消息
      this.typingTimer = setTimeout(() => {
        this.sendTypingMessage(false)
      }, 3000)
    },

    // 发送正在输入消息
    sendTypingMessage(isTyping) {
      if (this.websocket) {
        this.websocket.send({
          type: 'TYPING',
          toUserId: this.getTargetUserId(),
          isTyping: isTyping
        })
      }
    },

    // 选择图片
    chooseImage() {
      uni.chooseImage({
        count: 1,
        success: (res) => {
          // TODO: 上传图片并发送
          console.log('选择图片:', res.tempFilePaths[0])
        }
      })
    },

    // 拍照
    takePhoto() {
      uni.chooseImage({
        count: 1,
        sourceType: ['camera'],
        success: (res) => {
          // TODO: 上传图片并发送
          console.log('拍照:', res.tempFilePaths[0])
        }
      })
    },

    // 选择文件
    chooseFile() {
      // TODO: 实现文件选择
      uni.showToast({
        title: '功能开发中',
        icon: 'none'
      })
    },

    // 开始语音录制
    startVoiceRecord() {
      // TODO: 实现语音录制
      uni.showToast({
        title: '功能开发中',
        icon: 'none'
      })
    },

    // 预览图片
    previewImage(url) {
      uni.previewImage({
        urls: [url],
        current: url
      })
    },

    // 标记为已读
    async markAsRead() {
      // 如果没有会话ID，不需要标记已读
      if (!this.conversationId) {
        return
      }
      
      try {
        await markConversationAsRead(this.conversationId)
      } catch (error) {
        console.error('标记已读失败:', error)
      }
    },

    // 滚动到底部
    scrollToBottom() {
      if (this.messageList.length > 0) {
        const lastMessage = this.messageList[this.messageList.length - 1]
        this.scrollIntoView = `msg-${lastMessage.id}`
      }
    },

    // 判断是否为自己的消息
    isOwnMessage(message) {
      const userInfoStr = uni.getStorageSync('edu_user_info')
      const userInfo = userInfoStr ? JSON.parse(userInfoStr) : {userId: 1}
      
      // 转换为数字类型比较（避免类型不一致）
      const messageFromId = parseInt(message.fromUserId)
      const currentUserId = parseInt(userInfo.userId)  // 修改：使用userId字段
      
      const isOwn = messageFromId === currentUserId
      
      return isOwn
    },

    // 获取用户头像
    getUserAvatar(message) {
      const userInfoStr = uni.getStorageSync('edu_user_info')
      const userInfo = userInfoStr ? JSON.parse(userInfoStr) : {userId: 1}  // 已修复

      if (parseInt(message.fromUserId) === parseInt(userInfo.userId)) {
        // 自己的头像
        return userInfo.avatarUrl || '/static/icons/my-avatar.png'
      } else {
        // 对方的头像 - 优先使用otherUserInfo中的头像
        if (this.otherUserInfo && this.otherUserInfo.avatar) {
          return this.otherUserInfo.avatar
        }
        return '/static/icons/default-avatar.png'
      }
    },

    // 获取目标用户ID
    getTargetUserId() {
      // 优先使用targetUserId
      if (this.targetUserId) {
        console.log('使用targetUserId:', this.targetUserId)
        return this.targetUserId
      }
      
      // 如果是从教员列表进来的，返回教员ID
      if (this.teacherId) {
        console.log('使用teacherId:', this.teacherId)
        return this.teacherId
      }

      console.warn('未找到目标用户ID，无法发送消息')
      return null
    },

    // 是否显示时间
    shouldShowTime(message) {
      const index = this.messageList.findIndex(m => m.id === message.id)
      if (index === 0) return true // 第一条消息总是显示时间

      const prevMessage = this.messageList[index - 1]
      if (!prevMessage) return true

      // 如果与上一条消息间隔超过5分钟，显示时间
      const currentTime = new Date(message.createdAt).getTime()
      const prevTime = new Date(prevMessage.createdAt).getTime()
      return (currentTime - prevTime) > 5 * 60 * 1000 // 5分钟
    },

    // 格式化消息时间
    formatMessageTime(time) {
      return formatTime(time)
    },

    // 获取消息类型文本
    getMessageTypeText(contentType) {
      const typeMap = {
        'IMAGE': '[图片]',
        'FILE': '[文件]',
        'VOICE': '[语音]',
        'VIDEO': '[视频]'
      }
      return typeMap[contentType] || '[未知消息]'
    },

    // 处理更多操作
    handleMoreAction(action) {
      if (action.value === 'clear') {
        uni.showModal({
          title: '确认清空',
          content: '确定要清空聊天记录吗？',
          success: (res) => {
            if (res.confirm) {
              this.messageList = []
            }
          }
        })
      } else if (action.value === 'setting') {
        // TODO: 跳转到会话设置页面
        uni.showToast({
          title: '功能开发中',
          icon: 'none'
        })
      }
    },

    // 返回
    goBack() {
      uni.navigateBack()
    }
  }
}
</script>

<style lang="scss" scoped>
.chat-page {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f0f0f0;
  box-sizing: border-box;
}

/* 自定义导航栏样式 */
.custom-navbar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 999;
  background: linear-gradient(135deg, #66BB6A 0%, #4CAF50 100%);
  box-shadow: 0 4rpx 20rpx rgba(76, 175, 80, 0.25);
  backdrop-filter: blur(10px);

  /* 适配状态栏 */
  padding-top: var(--status-bar-height, 44px);

  .navbar-content {
    height: 88rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 30rpx;
    position: relative;
  }

  .navbar-left {
    width: 80rpx;
    height: 80rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);

    &:active {
      background-color: rgba(255, 255, 255, 0.15);
      transform: scale(0.95);
    }
  }

  .navbar-center {
    flex: 1;
    display: flex;
    justify-content: center;
    align-items: center;

    .chat-info {
      display: flex;
      flex-direction: column;
      align-items: center;

      .chat-title {
        color: #fff;
        font-size: 36rpx;
        font-weight: 600;
        line-height: 40rpx;
        text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.1);
      }

      .chat-status {
        color: rgba(255, 255, 255, 0.9);
        font-size: 24rpx;
        line-height: 28rpx;
        margin-top: 4rpx;
        padding: 2rpx 12rpx;
        background: rgba(255, 255, 255, 0.2);
        border-radius: 20rpx;
      }
    }
  }

  .navbar-right {
    width: 80rpx;
    height: 80rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);

    &:active {
      background-color: rgba(255, 255, 255, 0.15);
      transform: scale(0.95);
    }
  }
}

.message-list {
  flex: 1;
  padding: 20rpx 24rpx 40rpx 24rpx;
  overflow-y: auto;
  background: #f0f0f0;
  margin-bottom: 120rpx; /* 为输入框预留空间 */
}

.load-more-tip {
  display: flex;
  justify-content: center;
  padding: 20rpx 0;

  text {
    font-size: 24rpx;
    color: #999;
  }
}

.message-wrapper {
  margin-bottom: 20rpx;
}

.time-divider {
  display: flex;
  justify-content: center;
  margin: 20rpx 0 16rpx;

  .time-badge {
    background: rgba(0, 0, 0, 0.1);
    border-radius: 6rpx;
    padding: 6rpx 16rpx;
  }

  .time-text {
    color: #999;
    font-size: 24rpx;
  }
}

.message-item {
  display: flex;
  align-items: flex-start;
  margin-bottom: 24rpx;

  &.own-message {
    flex-direction: row-reverse;

    .message-content-wrapper {
      align-items: flex-end;
      margin-left: 0;
      margin-right: 16rpx;
    }

    .avatar-wrapper {
      margin-right: 0;
      margin-left: 16rpx;
    }
  }

  .avatar-wrapper {
    flex-shrink: 0;
    width: 80rpx;
    margin-right: 16rpx;
  }

  .message-content-wrapper {
    display: flex;
    flex-direction: column;
    max-width: 60%;
  }

  .text-message {
    background-color: #fff;
    padding: 16rpx 24rpx;
    border-radius: 8rpx;
    font-size: 30rpx;
    line-height: 1.6;
    word-wrap: break-word;
    position: relative;
    display: inline-block;

    .message-text {
      color: #000;
      word-break: break-all;
    }

    &.own-text {
      background: #95ec69;
      
      .message-text {
        color: #000;
      }
    }
  }

  .image-message {
    border-radius: 16rpx;
    overflow: hidden;
    box-shadow: 0 6rpx 16rpx rgba(0, 0, 0, 0.12);
    transition: transform 0.3s;

    image {
      width: 240rpx;
      height: 240rpx;
      display: block;
    }

    &:active {
      transform: scale(0.95);
    }
  }

  .other-message {
    background-color: #fff;
    padding: 24rpx 28rpx;
    border-radius: 24rpx;
    font-size: 28rpx;
    color: #666;
    text-align: center;
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
  }

  .message-status {
    margin-top: 8rpx;
    font-size: 24rpx;

    .status-sending {
      color: #999;
    }

    .status-sent {
      color: #999;
    }
  }
}


.typing-indicator {
  display: flex;
  align-items: center;
  padding: 20rpx 24rpx;
  margin-bottom: 20rpx;

  text {
    font-size: 24rpx;
    color: #999;
    margin-left: 16rpx;
    animation: fade 1.5s ease-in-out infinite;
  }

  &::before {
    content: '';
    width: 40rpx;
    height: 40rpx;
    border: 3rpx solid #4CAF50;
    border-radius: 50%;
    border-top-color: transparent;
    animation: spin 1s linear infinite;
  }
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

@keyframes fade {
  0%, 100% {
    opacity: 0.5;
  }
  50% {
    opacity: 1;
  }
}

.input-section {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-top: 1rpx solid rgba(0, 0, 0, 0.05);
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 100;
  box-shadow: 0 -4rpx 20rpx rgba(0, 0, 0, 0.08);
}

.input-bar {
  display: flex;
  align-items: center;
  padding: 16rpx 24rpx;
  gap: 16rpx;

  .icon-btn {
    width: 72rpx;
    height: 72rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
    transition: all 0.3s;

    &:active {
      background-color: #f0f0f0;
      transform: scale(0.95);
    }

    &.plus-btn {
      transition: transform 0.3s;
    }
  }

  .input-wrapper {
    flex: 1;

    /deep/ .u-input {
      background-color: #f8f8f8 !important;
      border-radius: 24rpx !important;
      min-height: 72rpx !important;
    }
  }

  .send-btn {
    width: 72rpx;
    height: 72rpx;
    background: linear-gradient(135deg, #66BB6A 0%, #4CAF50 100%);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    box-shadow: 0 4rpx 12rpx rgba(76, 175, 80, 0.4);
    transition: all 0.3s;
    animation: scaleIn 0.3s cubic-bezier(0.34, 1.56, 0.64, 1);

    &:active {
      transform: scale(0.9);
      box-shadow: 0 2rpx 8rpx rgba(76, 175, 80, 0.3);
    }
  }
}

@keyframes scaleIn {
  from {
    opacity: 0;
    transform: scale(0);
  }
  to {
    opacity: 1;
    transform: scale(1);
  }
}

.toolbar {
  display: flex;
  justify-content: space-around;
  padding: 32rpx 48rpx;
  border-top: 1rpx solid rgba(0, 0, 0, 0.05);
  background: #fff;

  .tool-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 12rpx;
    transition: all 0.3s;

    &:active {
      transform: translateY(-4rpx);
    }

    .tool-icon {
      width: 88rpx;
      height: 88rpx;
      border-radius: 20rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      box-shadow: 0 8rpx 16rpx rgba(0, 0, 0, 0.15);
      transition: all 0.3s;

      &:active {
        box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
      }
    }

    text {
      font-size: 24rpx;
      color: #666;
      font-weight: 500;
    }
  }
}

/* 工具栏动画 */
.toolbar-slide-enter-active,
.toolbar-slide-leave-active {
  transition: all 0.3s ease;
}

.toolbar-slide-enter-from {
  opacity: 0;
  transform: translateY(-20rpx);
}

.toolbar-slide-leave-to {
  opacity: 0;
  transform: translateY(-20rpx);
}
</style>
